package com.future.tenant.aop;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.future.tenant.TenantHolder;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
public class TenantFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String tenantId = request.getHeader("tenant_id");
            if (StrUtil.isNotBlank(tenantId) && NumberUtil.isNumber(tenantId)) {
                TenantHolder.setTenant(Long.valueOf(tenantId));
            }
            filterChain.doFilter(request, response);
        } finally {
            TenantHolder.clear();
        }
    }
}
